<template>
  <el-card id="usersHeader">
    <!-- 标题 -->
    <template #header>
      <h2>用户管理
        <el-button type="primary" class="btnAdd" @click="addDrawer=true">添加新用户</el-button>
      </h2>
    </template>
    <!-- 用户信息展示 -->
    <el-input placeholder="请输入搜索内容" v-model="searchValue">
      <el-select style="width: 100px" v-model="searchField" slot="prepend" placeholder="请选择">
        <el-option label="用户名" value="username"></el-option>
        <el-option label="手机" value="phone"></el-option>
        <el-option label="邮箱" value="email"></el-option>
      </el-select>
      <el-button @click="getUsers(params)" slot="append" icon="el-icon-search"></el-button>
    </el-input>

    <el-table v-loading="loading" :data="users" border stripe>
      <el-table-column align="center" prop="username" label="用户" width="100"></el-table-column>
      <el-table-column align="center" prop="gender" label="性别" width="50">
        <template #default="{row}">{{['女', '男'][row.gender]}}</template>
      </el-table-column>
      <el-table-column align="center" prop="phone" label="手机" width="120"></el-table-column>
      <el-table-column align="center" prop="email" label="邮箱" width="150"></el-table-column>
      <el-table-column align="center" prop="ctime" label="日期" width="100">
        <template #default="{row}">{{moment(row.ctime).locale('zh-cn').fromNow()}}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="250">
        <template #default="{row}">
          <el-button type="primary" plain @click="editShow(row)">
            编辑<i class="el-icon-edit"></i></el-button>
          <el-button type="danger" plain @click="del(row._id)">
            删除<i class="el-icon-delete"></i>
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @current-change="change" style="margin:15px 0" :page-size="perPage"
    background layout="prev, pager, next" :total="count"></el-pagination>

    <el-drawer v-loading="addLoading"
    size="400px" title="添加用户" :visible.sync="addDrawer" direction="rtl">
      <el-form style="padding:10px" :model="addForm" :rules="addRules" ref="addForm">
        <el-form-item label="用户" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="addForm.confirmPassword"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="addForm.phone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="addSave">保存</el-button>
          <el-button @click="addDrawer=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <el-drawer v-loading="editLoading"
    size="400px" title="编辑用户" :visible.sync="editDrawer" direction="rtl">
      <el-form style="padding:10px" :model="editForm" :rules="editRules" ref="editForm">
        <el-form-item label="用户" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="editForm.phone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editSave">保存</el-button>
          <el-button @click="editDrawer=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

  </el-card>
</template>

<script>
import { createNamespacedHelpers } from 'vuex';
import moment from 'moment';

const { mapActions, mapState } = createNamespacedHelpers('users');

export default {
  data() {
  // 用户信息 验证
    const validateUsername = async (rule, value, callback) => {
      const reg = /^\w{2,18}$/;
      if (reg.test(value)) {
        const { data } = await this.apis.usersExist({
          field: 'username',
          value,
        });
        if (!data) {
          callback();
        } else {
          callback(new Error('用户名已存在'));
        }
      } else {
        callback(new Error('用户名在2-18个字母和数字组合'));
      }
    };
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === this.addForm.password) {
        callback();
      } else {
        callback(new Error('两次密码不一致'));
      }
    };
    const validateEmail = async (rule, value, callback) => {
      const reg = /^\w{2,18}@\w{2,18}\.com$/;
      if (reg.test(value)) {
        const { data } = await this.apis.usersExist({
          field: 'email',
          value,
        });
        if (!data) {
          callback();
        } else {
          callback(new Error('邮箱已存在'));
        }
      } else {
        callback(new Error('邮箱格式错误'));
      }
    };
    const validatePhone = async (rule, value, callback) => {
      const reg = /^1[3456789]\d{9}$/;
      if (reg.test(value)) {
        const { data } = await this.apis.usersExist({
          field: 'phone',
          value,
        });
        if (!data) {
          callback();
        } else {
          callback(new Error('手机已存在'));
        }
      } else {
        callback(new Error('手机格式错误'));
      }
    };
    const editValidateUsername = (rule, value, callback) => {
      if (value === this.row.username) {
        callback();
      } else {
        validateUsername(rule, value, callback);
      }
    };
    const editValidateEmail = (rule, value, callback) => {
      if (value === this.row.email) {
        callback();
      } else {
        validateEmail(rule, value, callback);
      }
    };
    const editValidatePhone = (rule, value, callback) => {
      if (value === this.row.phone) {
        callback();
      } else {
        validatePhone(rule, value, callback);
      }
    };
    return {
      row: {},
      editForm: {
        username: '',
        gender: '',
        email: '',
        phone: '',
      },
      editLoading: false,
      editDrawer: false,
      addLoading: false,
      addForm: {
        gender: 1,
      },
      addDrawer: false,
      searchField: '',
      searchValue: '',
      perPage: 2,
      page: 1,
      // 用户信息编辑规则
      editRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: editValidateUsername, trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: editValidateEmail, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: editValidatePhone, trigger: 'blur' },
        ],
      },
      // 添加新用户验证规则
      addRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validateUsername, trigger: 'blur' },
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6, max: 18, message: '长度在6-18个字符', trigger: 'blur',
          },
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' },
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' },
        ],
      },
    };
  },
  computed: {
    params() {
      const p = {
        perPage: this.perPage,
        page: this.page,
      };
      if (this.searchField && this.searchValue) {
        p.searchField = this.searchField;
        p.searchValue = this.searchValue;
      }
      return p;
    },
    ...mapState(['count', 'users', 'loading']),
  },
  created() {
    this.getUsers(this.params);
  },
  methods: {
    // 删除用户
    del(id) {
      this.$confirm('确定删除吗？').then(async () => {
        await this.apis.deleteUser(id);
        this.getUsers(this.params);
      }).catch(() => {});
    },
    // 保存编辑用户信息
    editSave() {
      this.$refs.editForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        this.editLoading = true;
        const { _id: id } = this.row;
        const data = {};
        if (this.editForm.username !== this.row.username) {
          data.username = this.editForm.username;
        }
        if (this.editForm.gender !== this.row.gender) {
          data.gender = this.editForm.gender;
        }
        if (this.editForm.email !== this.row.email) {
          data.email = this.editForm.email;
        }
        if (this.editForm.phone !== this.row.phone) {
          data.phone = this.editForm.phone;
        }
        await this.apis.editUser(id, data);
        this.getUsers(this.params);
        this.editLoading = false;
        this.editDrawer = false;
      });
    },
    // 编辑用户信息的数据展示
    editShow(row) {
      this.row = row;
      this.editDrawer = true;
      this.editForm.username = row.username;
      this.editForm.gender = row.gender;
      this.editForm.phone = row.phone;
      this.editForm.email = row.email;
    },
    // 保存添加新用户
    addSave() {
      this.$refs.addForm.validate(async (valid) => {
        if (!valid) {
          return;
        }
        this.addLoading = true;
        await this.apis.addUser({
          username: this.addForm.username,
          password: this.addForm.password,
          gender: this.addForm.gender,
          email: this.addForm.email,
          phone: this.addForm.phone,
        }).catch(() => {
          this.addLoading = false;
        });
        this.getUsers(this.params);
        this.addLoading = false;
        this.addDrawer = false;
      });
    },
    change(e) {
      this.page = e;
      this.getUsers(this.params);
    },
    moment,
    ...mapActions(['getUsers']),
  },
};
</script>

<style lang="scss" scoped>
  #usersHeader{
    .btnAdd{
      width: 85px;
      height: 20px;
      padding: 0;
      text-align: center;
    }
  }
</style>
